import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/home/authorize_bean.dart';
import 'package:opene/login/login.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:io' show Platform;
import 'app_main/app_main.dart';

void main() {
  // startup();
  // WidgetsFlutterBinding.ensureInitialized(); // 确保绑定已初始化
  // SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: []);
  // SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp, DeviceOrientation.portraitUp]);
  // 解决报错 PlatformException(channel-error, Unable to establish connection on channel., null, null)
  // SharedPreferences.setMockInitialValues({});
  // requestPermissions();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: WelcomePage(),
      builder: (context, widget) {
        return MediaQuery(
          //设置全局的文字的textScaleFactor为1.0，文字不再随系统设置改变
          data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
          child: widget,
        );
      },
    );
    // return MaterialApp(
    //   home: WelcomePage(),
    // );
  }
}

class WelcomePage extends StatefulWidget {
  @override
  _WelcomePageState createState() => _WelcomePageState();
}

class _WelcomePageState extends State<WelcomePage> {


  @override
  Widget build(BuildContext context) {
    Utils.getSharedPreferenceString(Constants.token).then((value) => {
          Constants.tokenValue = value,
          if (Constants.tokenValue == null)
            {
              Navigator.pushAndRemoveUntil(
                context,
                MaterialPageRoute(builder: (context) => Login()),
                (route) => route == null,
              )
            }
          else
            {
              Navigator.pushAndRemoveUntil(
                context,
                MaterialPageRoute(builder: (context) => MyAppMain()),
                (route) => route == null,
              )
            }
        });

    return Scaffold(
        appBar: null,
        body: Container(
          color: MyAppTheme.nearlyBlue,
        ));
  }

}

Future<void> startup() async {
  // List<Permission> permissionNames = [];
  // permissionNames.add(Permission.location);
  // permissionNames.add(Permission.camera);
  // permissionNames.add(Permission.storage);
  // checkAndRequestPermission(Permission.camera);
  getStoragePermission();
}

void checkAndRequestPermission(Permission permission) async {
  PermissionStatus status = await permission.status;
  if (!status.isGranted) {
    status = await permission.request();
  }
  if (status.isGranted) {
    // 权限已授予，可以执行相关操作
  } else {
    // 权限被拒绝或永久拒绝
    await openAppSettings();
  }
}

/// 获取存储权限
Future<bool> getStoragePermission() async {
  Map<Permission, PermissionStatus> permissions = await [
    Permission.camera,
  ].request();

  //  PermissionStatus myPermission;
  //
  // /// 读取系统权限
  // if (Platform.isIOS) {
  //   myPermission = await Permission.camera.request();
  // } else {
  //   myPermission = await Permission.camera.request();
  // }
  // // if (Platform.isIOS) {
  // //   myPermission = await Permission.photosAddOnly.request();
  // // } else {
  // //   myPermission = await Permission.storage.request();
  // // }
  // if (myPermission != PermissionStatus.granted) {
  //   return false;
  // } else {
  //   return true;
  // }
}

void checkPermission() async {
  // 请求存储权限
  final permissionState = await getStoragePermission();
  if (permissionState) {
    // 权限被授予
  } else {
    // 权限被拒绝 打开手机上该App的权限设置页面
    openAppSettings();
  }
}

void requestPermissions() async {
  Map<Permission, PermissionStatus> statuses = await [
    Permission.location,
    Permission.storage,
    // Permission.camera,
  ].request();

  print('位置权限：${statuses[Permission.location]}');
  print('存储权限：${statuses[Permission.storage]}');
}

void requestPermission(Permission permission) async {
  //发起权限申请
  PermissionStatus status = await permission.request();
  // 返回权限申请的状态 status
  print('权限状态$status');
  if (status.isPermanentlyDenied) {
    openAppSettings();
  }
}
